package com.chensheng.controller;

import com.chensheng.converter.OrderForm2OrderDTO;
import com.chensheng.converter.OrderMaster2OrderDTO;
import com.chensheng.dto.OrderDTO;
import com.chensheng.dto.ResultDTO;
import com.chensheng.enums.OrderStatusEnum;
import com.chensheng.enums.ResultErrorEnum;
import com.chensheng.exception.SellException;
import com.chensheng.form.OrderForm;
import com.chensheng.model.OrderDetail;
import com.chensheng.model.OrderMaster;
import com.chensheng.service.OrderDetailService;
import com.chensheng.service.OrderMasterService;
import com.chensheng.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author:ChenSheng
 * @Description:
 * @Date: Created in 上午 10:15 2018/5/15 0015
 */
@RestController
@Slf4j
@RequestMapping("/buyer/order")
public class BuyerOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMasterService orderMasterService;

    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/create")
    public ResultDTO<Map<String, String>> create(@Valid OrderForm orderForm,
                                                 BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【创建订单】Error:{}, orderForm={}", ResultErrorEnum.FORM_PARAMS_ERROR.getMsg(), orderForm);
            throw new SellException(ResultErrorEnum.FORM_PARAMS_ERROR);
        }

        OrderDTO orderDTO = OrderForm2OrderDTO.convert(orderForm);
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("【创建订单】Error: {}", ResultErrorEnum.CART_EMPTY_ERROR.getMsg());
            throw new SellException(ResultErrorEnum.CART_EMPTY_ERROR);
        }

        //调用order_master
        String orderId = orderService.create(orderDTO);

        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        return ResultDTO.success(map);
    }

    @GetMapping("/list")
    public ResultDTO<List<OrderDTO>> list(@RequestParam("openid") String openid,
                                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                                          @RequestParam(value = "size", defaultValue = "10") Integer size){
        if(StringUtils.isEmpty(openid)){
            log.error("【查询订单】Error:{}", ResultErrorEnum.OPENID_EMPTY_ERROR.getMsg());
            throw new SellException(ResultErrorEnum.OPENID_EMPTY_ERROR);
        }
        Integer start = (page - 1) * size;
        Integer offset = size;

        List<OrderMaster> orderMasterList = orderMasterService.findOneByOpenid(openid, start, offset);
        List<OrderDTO> orderDTOList = orderMasterList.stream()
                .map(e-> OrderMaster2OrderDTO.convert(e)).collect(Collectors.toList());

        return ResultDTO.success(orderDTOList);
    }

    @GetMapping("/detail")
    public ResultDTO<OrderDTO> detail(@RequestParam("openid") String openid,
                                      @RequestParam("orderId") String orderId){
        if(StringUtils.isEmpty(openid) || StringUtils.isEmpty(orderId)){
            log.error("【查询订单】Error:{}", ResultErrorEnum.FORM_PARAMS_ERROR.getMsg());
            throw new SellException(ResultErrorEnum.FORM_PARAMS_ERROR);
        }

        OrderMaster orderMaster = orderMasterService.findOneByOrderId(orderId);
        if(!orderMaster.getBuyerOpenid().equals(openid)){
            log.error("【查询订单】Error:{}", ResultErrorEnum.ORDER_OWNER_ERROR.getMsg());
            throw new SellException(ResultErrorEnum.ORDER_OWNER_ERROR);
        }
        List<OrderDetail> orderDetailList = orderDetailService.findByOrderId(orderId);

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return ResultDTO.success(orderDTO);
    }

    @PostMapping("/cancel")
    public ResultDTO cancel(@RequestParam("openid") String openid,
                            @RequestParam("orderId") String orderId){
        if(StringUtils.isEmpty(openid) || StringUtils.isEmpty(orderId)){
            log.error("【取消订单】Error:{}", ResultErrorEnum.FORM_PARAMS_ERROR.getMsg());
            throw new SellException(ResultErrorEnum.FORM_PARAMS_ERROR);
        }
        OrderMaster orderMaster = orderMasterService.findOneByOrderId(orderId);
        if(ObjectUtils.isEmpty(orderMaster)){
            log.error("【取消订单】订单不存在");
            throw new SellException(ResultErrorEnum.ORDER_NOT_EXIST_ERROR);
        }
        if(!orderMaster.getBuyerOpenid().equals(openid)){
            log.error("【取消订单】Error:{}", ResultErrorEnum.ORDER_OWNER_ERROR.getMsg());
            throw new SellException(ResultErrorEnum.ORDER_OWNER_ERROR);
        }

        if (!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【取消订单】Error:{}", ResultErrorEnum.ORDER_STATUS_ERROR.getMsg());
            throw new SellException(ResultErrorEnum.ORDER_STATUS_ERROR);
        }

        orderService.cancel(orderMaster);
        return ResultDTO.success(null);
    }

}
